import React from 'react'
import PropTypes from 'prop-types'
import { NavLink } from 'react-router-dom'
import _ from 'lodash'
import { Icon, Menu } from 'antd'
import view from '../../view'
import store from '../../store'
import style from './SideMenu.styl'

// const icons = requireAll(require.context('./images/menu-icon', false, /\.png$/))
class SideMenu extends React.Component {
    static defaultProps = {
        location: {},
    }

    static propTypes = {
        location: PropTypes.object,
    }

    constructor(props) {
        super(props)
        this.state = {
            collapsed: false,
        }
    }

    onTriggerClik = () => {
        this.setState({
            collapsed: !this.state.collapsed,
        })
    }

    mapViewToLinks = ({ subs = [], path = '' }, levelOne) => {
        const accessibleSubs = subs.filter(sub => ['*'].concat(store.getState()['APP.PERMISSION']).includes(_.get(sub, 'meta.access', '*')))
        const visibleSubs = accessibleSubs.filter(sub => _.get(sub, 'meta.visible', true))

        return visibleSubs.map(sub => ({ ...sub, path: path + sub.path })).map(sub => {
            const hasSubs = _.has(sub, 'subs[0]', false)
            return hasSubs ?
                <Menu.SubMenu key={sub.path} title={<span><Icon type={sub.icon} /><span>{sub.label}</span></span>}>
                    { this.mapViewToLinks(sub) }
                </Menu.SubMenu> :
                <Menu.Item key={sub.path} to={sub.path} meta={sub.meta}>
                    <NavLink to={sub.path}>
                        {levelOne && <Icon type={sub.icon} />}
                        <span>{sub.label}</span>
                    </NavLink>
                </Menu.Item>
        })
    }

    render() {
        const { location: { pathname } } = this.props
        const { collapsed } = this.state
        return (
            <div className={style.menu}>
                <Menu
                    selectedKeys={[pathname]}
                    mode="inline"
                    theme="dark"
                    inlineCollapsed={collapsed}
                    style={{ height: '100%', overflowY: 'auto' }}
                >
                    { this.mapViewToLinks({ subs: view.roots }, true) }
                </Menu>
                <div className={style.switch} onClick={this.onTriggerClik}>
                    <Icon type={collapsed ? 'right' : 'left'} theme="outlined" />
                </div>
            </div>
        )
    }
}

export default SideMenu
